package lib

import (
	"path"

	"golang.org/x/sys/windows/registry"
	"gopkg.in/ini.v1"
)

const (
	reg_path = `Software\Microsoft\Windows\CurrentVersion\Run`
	reg_key  = "eyecare.refusea.com"
)

type Settings struct {
	StartupNotify bool
	StartupStatus bool

	WorkTime   int
	BreakTime  int
	RemindTime int

	FullscreenDetermine bool
}

func LoadSettings() Settings {

	cfg, err := ini.Load(path.Join(Dir, "eyecare.ini"))
	if err != nil {

		print("load setting error:", err.Error())

		return Settings{
			StartupNotify:       true,
			StartupStatus:       getStartupStatus(Fullpath),
			WorkTime:            45,
			BreakTime:           3,
			RemindTime:          30,
			FullscreenDetermine: true,
		}
	}

	return Settings{
		StartupNotify:       cfg.Section("startup").Key("notify").MustBool(true),
		StartupStatus:       getStartupStatus(Fullpath),
		WorkTime:            cfg.Section("time").Key("work").MustInt(45),
		BreakTime:           cfg.Section("time").Key("break").MustInt(3),
		RemindTime:          cfg.Section("time").Key("remind").MustInt(30),
		FullscreenDetermine: cfg.Section("fullscreen").Key("determine").MustBool(true),
	}
}

func getStartupStatus(fullpath string) bool {
	k, err := registry.OpenKey(registry.CURRENT_USER, reg_path, registry.QUERY_VALUE)
	if err != nil {
		return false
	}
	defer k.Close()

	v, _, err := k.GetStringValue(reg_key)
	return err == nil && v == fullpath
}

func (s *Settings) ToggleStartupStatus() error {

	k, err := registry.OpenKey(registry.CURRENT_USER, reg_path, registry.SET_VALUE)
	if err != nil {
		return err
	}
	defer k.Close()

	if s.StartupStatus {
		err = k.DeleteValue(reg_key)
	} else {
		err = k.SetStringValue(reg_key, Fullpath)
	}

	if err == nil {
		s.StartupStatus = !s.StartupStatus
	}

	return err
}
